package com.gatewaydy.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gatewaydy.dao.GatewayMapper;
import com.gatewaydy.entity.GatewayInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: LCG
 * @date: 2022-10-27 11:33:24
 * @description:  这个类用来跟数据库进行数据库的交互 crud 持久化的路由信息
 **/
@Service
public class GatewayService extends ServiceImpl<GatewayMapper,GatewayInfo> {

   @Autowired
   private GatewayMapper gatewayMapper;

   public List<GatewayInfo> getGatewayInfoList(String group){
       LambdaQueryWrapper<GatewayInfo> queryWrapper = Wrappers.lambdaQuery(GatewayInfo.class)
               .select()
               .eq(true,GatewayInfo::getGroupInfo,group);
        List<GatewayInfo> gatewayInfos = gatewayMapper.selectList(queryWrapper);
        return gatewayInfos;
   }

   public int saveRoute(RouteDefinition routeDefinition){
       GatewayInfo gatewayInfo=new GatewayInfo();
       gatewayInfo.setGatewayInfo(JSON.toJSONString(routeDefinition));
       gatewayInfo.setGroupInfo("g1");
       gatewayInfo.setServiceId(routeDefinition.getId());
       //构造更新条件
       LambdaQueryWrapper<GatewayInfo> queryWrapper = Wrappers.lambdaQuery(GatewayInfo.class)
               .select()
               .eq(true, GatewayInfo::getServiceId, routeDefinition.getId())
               .eq(true,GatewayInfo::getGroupInfo,"g1");
       //查询当前保存的路由信息是不是存在
       GatewayInfo gatewayInfo1 = gatewayMapper.selectOne(queryWrapper);
       if(gatewayInfo1!=null){
           LambdaUpdateWrapper<GatewayInfo> updateWrapper = Wrappers.lambdaUpdate(GatewayInfo.class)
                   .set(true, GatewayInfo::getGatewayInfo, gatewayInfo.getGatewayInfo())
                   .eq(GatewayInfo::getId, gatewayInfo1.getId());
           return gatewayMapper.update(gatewayInfo1,updateWrapper);
       }else{
           return gatewayMapper.insert(gatewayInfo);
       }
   }

   public int deleteRoutes(String serviceId,String gourpInfo){

       LambdaQueryWrapper<GatewayInfo> queryWrapper = Wrappers.lambdaQuery(GatewayInfo.class)
               .eq(true, GatewayInfo::getGroupInfo, gourpInfo)
               .eq(true, GatewayInfo::getServiceId, serviceId);

       return gatewayMapper.delete(queryWrapper);
   }


}
